<template>
	<view>
		<!-- 未打卡显示 -->
		<view v-if="status == 0">
			<view class="content" v-for="(item,index) in questions" :key="index">
				<view class="topic">第{{index + 1}}题</view>
				<view class="question">
					<text>{{item.title}}</text>
					<text class="tips">（{{item.tips}}）</text>
				</view>
				<view class="answer">
					<!-- 单选题 -->
					<view v-if="item.showtype == 0">
						<u-radio-group
							placement="column"
						>
							<u-radio
								:customStyle="{marginBottom: '12px'}"
								v-for="(radioItem, radioIndex) in item.radios"
								:key="radioIndex"
								:label="radioItem.name"
								:name="radioItem.name"
								labelSize=32rpx
								size=32rpx
								@change="radioChange(index,radioItem.name)"
							>
							</u-radio>
						</u-radio-group>
					</view>

					<!-- 上传图片 -->
					<view v-if="item.showtype == 1">
						<u-upload
							:fileList="item.fileList"
							@afterRead="afterRead(index,$event)"
							@delete="deletePic"
							name="name"
							multiple
							:maxCount="1"
							:previewFullImage="true"
							width="100"
	            height="100"
						></u-upload>
					</view>

					<!-- 文本框 -->
					<view v-if="item.showtype == 2">
						<u--textarea v-model="item.answer" placeholder="请输入内容" @input="textInput(index,$event)" ></u--textarea>
					</view>
				</view>

				<!-- 没有更多了 -->
				<view class="nomore" v-if="index == questions.length-1">没有更多了</view>
				<u-line></u-line>
			</view>

			<!-- 定位 -->
			<view class="location">
				<view class="locationTitle">定位</view>
				<view style="font-size: 32rpx;">{{position}}</view>
			</view>
			<u-line></u-line>
			<button class="btn" @click="submit">提交</button>
			<!-- 提示信息弹窗 -->
			<u-toast ref="uToast"></u-toast>
	  </view>

    <!-- 已打卡显示 -->
		<view v-else-if="status == 1">
			<view class="content" v-for="(item,index) in questions" :key="index">
				<view class="topic">第{{index + 1}}题</view>
				<view class="question">
					<text>{{item.title}}</text>
					<text class="tips">（{{item.tips}}）</text>
				</view>
				<view class="answer">
					<!-- 单选题 -->
					<view v-if="item.showtype == 0">
						<u-radio-group
							placement="column"
							v-model="item.answer"
							@change="groupChange"
						>
							<u-radio
								:customStyle="{marginBottom: '12px'}"
								v-for="(radioItem, radioIndex) in item.radios"
								:key="radioIndex"
								:label="radioItem.name"
								:name="radioItem.name"
								:disabled="true"
								labelSize=32rpx
								size=32rpx
								@change="radioChange(index,radioItem.name)"
							>
							</u-radio>
						</u-radio-group>
					</view>

					<!-- 上传图片 -->
					<!-- <view v-if="item.showtype == 1">
						<image :src="imgUrl" style="width: 100rpx; height:100rpx"></image>
					</view> -->
					<view v-if="item.showtype == 1">
						<u-upload
							:fileList="item.fileList"
							name="name"
							multiple
							:maxCount="1"
							:previewFullImage="true"
							width="100"
	            height="100"
						></u-upload>
					</view>

					<!-- 文本框 -->
					<view v-if="item.showtype == 2">
						<u--textarea v-model="item.answer" placeholder="请输入内容" :disabled="true" ></u--textarea>
					</view>
				</view>

				<!-- 没有更多了 -->
				<view class="nomore" v-if="index == questions.length-1">没有更多了</view>
				<u-line></u-line>
			</view>

			<!-- 定位 -->
			<view class="position">
				<view class="positionTitle">定位</view>
				<view style="font-size: 32rpx;">{{position}}</view>
			</view>
			<u-line></u-line>
			<button class="btn" :disabled="true">提交</button>
	</view>
	</view>
</template>

<script>
  var QQMapWX = require('../../../../lib/qqmap-wx-jssdk.min.js');
  var qqmapsdk;
	export default {
		
		onLoad(op) {
			let that = this;
			uni.getStorage({
				key:'studentId',
				success: function (res) {
				that.id = res.data;
			}
			})
			//查询是否打卡
			let time = new Date();
			let timeObj = {};
			timeObj.year = time.getFullYear();
			timeObj.month = (time.getMonth() + 1) >= 1 && (time.getMonth() + 1) <= 9 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
			timeObj.day = time.getDate() >= 0 && time.getDate() <= 9 ? ("0" + time.getDate()) : time.getDate();
			const datetime = timeObj.year + '-' + timeObj.month + '-' + timeObj.day;
			console.log(op.id);
			uni.request({
				url: 'http://localhost:8123/record/listOne',
				method:'GET',  
				data: {
					student: op.id,
					datetime: datetime
				},
				success: (res => {
					//console.log(11,res);
					//如果今天打卡了
					if (res.data.data) {
						console.log(JSON.parse(res.data.data.value));
						const answer = JSON.parse(res.data.data.value);
						that.status = res.data.data.status;
						that.questions[0].answer = answer[1].val;
						that.questions[1].fileList.push({url:"http://localhost:8123/image/"+answer[2].val})
						that.questions[2].fileList.push({url:"http://localhost:8123/image/"+answer[3].val})
						that.questions[3].answer = answer[4].val;
						that.questions[4].answer = answer[5].val;
						that.questions[5].answer = answer[6].val;
						that.position = answer[0].val;
						// let imageUrl_2 = {
						// 	url: "http://localhost:8123/image/"+id+"/"+datetime+"_"+"2"
						// }
						// let imageUrl_3 = {
						// 	url: "http://localhost:8123/image/"+id+"/"+datetime+"_"+"3"
						// }

					} else {
						//如果今天没打卡
						that.status = 0;
					}
				})
			})

			//获取定位的具体信息
			qqmapsdk = new QQMapWX({
        key: "64TBZ-KLXC6-4TAS6-M6IAI-UL3JE-WUF3N"
			})
			uni.getLocation({  
				type: 'wgs84',
				geocode:true,
					success: function (res) {  
						// console.log(res);
						// console.log('当前位置的经度：' + res.longitude);  
						// console.log('当前位置的纬度：' + res.latitude);  
						const longitude = res.longitude;
						const latitude = res.latitude;
						qqmapsdk.reverseGeocoder({
							location:{
								latitude:latitude,
								longitude:longitude
							},
							success:function(res){
								//console.log(res);
								// console.log(that.position);
								//得到详细对象
								let result = res.result;
								//从省份到县城再到某一路的位置信息
								that.position = result.address;
								//将上面信息变成JSON对象
								let addressComponent = result.address_component;
								//国家
								let nation = addressComponent.nation;
								//省份
								let province = addressComponent.province;
								//市级单位
								let city = addressComponent.city;
								//县级别单位
								let district = addressComponent.district;
							}
						})
					},
				fail(e) {
					//console.log(e);
				},
			});
	  },
		// created() {
		// 	//获取地理位置
		// 	uni.getStorage({
		// 		key: '111111',
		// 		success: ((res) => {console.log(res.data);this.location=res.data})
		// 	});
		// },
		data() {
			return {
				id:'',
				//打卡的具体问题
				questions: [
					// showtype:0 单选题
					// showtype:1 上传图片
					// showtype:2 文本输入
					// fileList:图片保存
					// text:文本框保存
					// tips:问题后面的提示
				{
					title:'当天体温',
				  showtype:0, 
					radios:[
						{name:'低于37.3度', disabled: false},
						{name:'高于37.3度', disabled: false}
					],
					fileList: [],
					tips:'单选题',
					answer:''
				},
				{
					title:'当天天津健康码截图', 
					showtype:1,
					radios:[],
					fileList: [],
					tips:'上传图片',
					answer:''
				},
				{
					title:'当天大数据行程卡截图', 
					showtype:1,
					radios:[],
					fileList: [],
					tips:'上传图片',
					answer:''
				},
				{
					title:'当天是否外出（跨市）？如有请详细描述', 
					showtype:2,
					radios:[],
					fileList: [],
					tips:'文本输入',
					answer:''
				},
				{
					title:'是否是管控地区？', 
					showtype:0,
					radios:[
						{name:'是', disabled: false},
						{name:'否', disabled: false}
					],
					fileList: [],
					tips:'单选题',
					answer:''
				},
				{
					title:'14日内，是否具有高中风险地区旅居史？', 
					showtype:0,
					radios:[
						{name:'是', disabled: false},
						{name:'否', disabled: false}
					],
					fileList: [],
					tips:'单选题',
					answer:''
				}
				],
				//打卡定位
				position: '',
				//是否已打卡  0是未打卡,1是已打卡
				status: undefined,
				//提交打卡时间
				detailTime: {},
				//打卡成功弹出框
				toast: {
					type: 'default',
					message: "提交成功",
					url: '../index',
				},
				//传给后端数据
				response: {
					datetime: '',
					student: '',
					value: []
				},
				date:''
			}
		},
		methods: {
						// 文本框
			textInput(index,e) {
				//console.log(index,e);
				this.questions[index].answer = e;
				this.response.value.push({id: index + 1 + '', val: e});
			},

			// 时间格式化
			getTime() {
				let time = new Date();
				this.detailTime.year = time.getFullYear();
				this.detailTime.month = (time.getMonth() + 1) >= 1 && (time.getMonth() + 1) <= 9 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
				this.detailTime.day = time.getDate() >= 0 && time.getDate() <= 9 ? ("0" + time.getDate()) : time.getDate();
				this.detailTime.hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
				this.detailTime.minute = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
				this.detailTime.second = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
				// console.log(this.detailTime);
				// let timeList = {};
				this.response.datetime = this.detailTime.year + '-' + this.detailTime.month + '-' + this.detailTime.day + ' ' + this.detailTime.hour + ':' + this.detailTime.minute + ':' + this.detailTime.second;
				//timeList.hour = this.detailTime.hour + ':' + this.detailTime.minute + ':' + this.detailTime.second;
				//console.log(timeList);
			},
				getDate() {
				let time = new Date();
				this.detailTime.year = time.getFullYear();
				this.detailTime.month = (time.getMonth() + 1) >= 1 && (time.getMonth() + 1) <= 9 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
				this.detailTime.day = time.getDate() >= 0 && time.getDate() <= 9 ? ("0" + time.getDate()) : time.getDate();
				this.detailTime.hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
				this.detailTime.minute = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
				this.detailTime.second = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
				// console.log(this.detailTime);
				// let timeList = {};
				this.date = this.detailTime.year + '-' + this.detailTime.month + '-' + this.detailTime.day;
				//timeList.hour = this.detailTime.hour + ':' + this.detailTime.minute + ':' + this.detailTime.second;
				//console.log(timeList);
			},

			//提交按钮
			submit() {
				let that_ = this;
				uni.getStorage({
					key:'studentId',
					success: function(res){
						that_.id = res.data
					}
				})
				//消息提示框
				const toast = this.toast;
				//传给后端数据
				this.response.student = this.id; //学生id
				this.response.value.unshift({id: 0 + '', val: this.position}); //定位保存在id=0
				this.getTime();//获取打卡时间
				this.response.value = JSON.stringify(this.response.value) //把答案数组保存为json格式的
				const record = this.response; //把整个回答保存为record
				//console.log(record);
				wx.request({
					url: 'http://localhost:8123/record/add', //仅为示例，并非真实接口地址。
					data: {
							datetime: record.datetime,
							student: record.student,
							value:record.value
					},
					method: 'POST',
					header: {
					},
					success: res =>{
						//console.log(res);
						//消息提示框
						this.$refs.uToast.show({
							...toast,
							complete() {
								//跳转至首页
								console.log(toast.url);
								toast.url && uni.switchTab({
									url: toast.url,
									success: res =>{console.log(res)},
									fail:err=>{
										console.log(err)
									}
								})
							}
					  })
				  }
			  }) 
		  },
			// 单选框
			// groupChange(n) {
      //   console.log('groupChange', n);
      // },
      radioChange(index,name) {
				// console.log(name,index);
				this.questions[index].answer = name;
				this.response.value.push({id: index + 1 + '', val: name});
				//console.log(this.response)
				// console.log(this.questions);
        // console.log('radioChange', name);
      },


			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(index,event) {
				//console.log(index);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				//console.log(event)
				let lists = [].concat(event.file)
				//console.log(lists)
				let fileListLen = this.questions[index].fileList.length
				// console.log(lists,fileListLen);
				lists.map((item) => {
					this.questions[index].fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,index)
					let item = this.questions[index].fileList[fileListLen]
					this.questions[index].fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url,index) {
				let that = this;
				uni.getStorage({
					key:'studentId',
					success: function(res){
						that.id = res.data
					}
				})
				// console.log(this.id);
				//消息提示框
				//传给后端数据
				this.getDate();//获取打卡时间
				console.log(this.id +"/"+ this.date);
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://localhost:8123/record/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							id: index + 1,
							num :that.id,
							datetime:that.date
						},
						//uploadFile成功
						success: (res) => {
							//console.log(res);
							//console.log(JSON.parse(res.data).msg);
							that.questions[index].fileList[0].url = 'http://localhost:8123/' + JSON.parse(res.data).msg;
							that.response.value.push({id:index+1,val:JSON.parse(res.data).msg})
							//promise成功的回调
							resolve(res.data.msg);
						}
					});
				})
			},
		},
  }
</script>

<style>
.content {
	margin-right: 5%;
	margin-left: 5%;
}
.topic {
	margin-top: 5%;
	margin-bottom: 1%;
	font-size: 32rpx;
	font-weight: 550;
}
.tips {
	color: rgb(185, 197, 198);
}
.question {
	margin-bottom: 3%;
	font-size: 32rpx;
}
.answer {
	margin-bottom: 5%;
	font-size: 32rpx;
}
.nomore {
	color: rgb(185, 197, 198);
	text-align: center;
}
.location {
	margin: 5%;
}
.locationTitle {
	margin-bottom: 1%;
	font-size: 34rpx;
}
.position {
	margin: 5%;
}
.positionTitle {
	margin-bottom: 1%;
	font-size: 34rpx;
}
.btn {
	margin-top: 5%;
	margin-bottom: 5%;
	width: 80%;
	background-color: rgb(255, 255, 255);
	color: rgb(0, 162, 255);
}
</style>
